package com.chat.controller;

import com.chat.enums.OperatorFriendRequestTypeEnum;
import com.chat.enums.SearchFriendsStatusEnum;
import com.chat.pojo.Users;
import com.chat.pojo.bo.UsersBO;
import com.chat.pojo.vo.MyFriendsVO;
import com.chat.pojo.vo.UsersVO;
import com.chat.service.UserService;
import com.chat.utils.FastDFSClient;
import com.chat.utils.FileUtils;
import com.chat.utils.IMoocJSONResult;
import com.chat.utils.MD5Utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.jni.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService service;

    @Autowired
    private FastDFSClient fastDFSClient;

    /**
     * 登录或注册
     * @param user
     * @return
     * @throws Exception
     */
    @PostMapping("/registOrLogin")
    public IMoocJSONResult registOrLogin(@RequestBody Users user) throws Exception{
        System.out.println("一个访问拿进来了：" + user.getUsername());
        //判断用户名或密码是否为空
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            return IMoocJSONResult.errorMsg("用户名或密码不能为空...");
        }

        boolean userIsExist = service.queryUserIsExist(user.getUsername());
        Users result = null;
        //判断用户是否已存在
        if (userIsExist) {
            //登录
            result = service.queryUserLogin(user.getUsername(),
                            MD5Utils.getMD5Str(user.getPassword()));
            if (result == null) {
                return IMoocJSONResult.errorMsg("用户名或密码不正确...");
            }
        }else {
            //注册
            user.setNickname(user.getUsername());
            user.setFaceImage("");
            user.setFaceImageBig("");
            user.setPassword(MD5Utils.getMD5Str(user.getPassword()));

            result = service.userRegist(user);
        }
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(usersVO,result);

        return IMoocJSONResult.ok(usersVO);
    }

    /**
     * 更新用户头像
     * @param userBO
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadFaceBase64")
    public IMoocJSONResult uploadFaceBase64(@RequestBody UsersBO userBO) throws Exception {
        //获取前段传过来的base64字符串，转换成文件对象再上传
        String base64Data = userBO.getFaceData();
        String userFacePath = "C:\\" + userBO.getUserId() + "userface64.png";
        FileUtils.base64ToFile(userFacePath,base64Data);

        //将路径对应的文件转化成MultipartFile
        MultipartFile faceFile = FileUtils.fileToMultipart(userFacePath);
        //上传文件到fastDFS
        //返回的是路径
        String url = fastDFSClient.uploadBase64(faceFile);
        System.out.println(url);

        //获得缩略图的url
        String thump = "_80x80.";
        String arr[] = url.split("\\.");
        String thumpImgUrl = arr[0] + thump + arr[1];

        //更新用户的头像信息
        Users user = new Users();
        user.setId(userBO.getUserId());
        user.setFaceImage(thumpImgUrl);
        user.setFaceImageBig(url);

        //删除本地临时文件
        try {
            Files.delete(Paths.get(userFacePath));
        } catch (IOException e) {
            System.err.println("文件未删除成功：" + userFacePath);
        }

        //更新并返回最新的用户信息
        Users result = service.updateUserInfo(user);

        return IMoocJSONResult.ok(result);
    }

    @PostMapping("/setNickname")
    public IMoocJSONResult setNickname(@RequestBody UsersBO userBO) {
        //更新用户的头像信息
        System.out.println("用户nickname：" + userBO.getNickname());
        Users user = new Users();
        System.out.println(userBO.getUserId());
        user.setId(userBO.getUserId());
        user.setNickname(userBO.getNickname());
        System.out.println(user);

        //更新并返回最新的用户信息
        Users result = service.updateUserInfo(user);

        return IMoocJSONResult.ok(result);
    }

    @PostMapping("/search")
    public IMoocJSONResult searchUser(String myUserId, String friendUsername) throws InvocationTargetException, IllegalAccessException {
        // 0、判断参数是否为空
        if (StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUsername)) {
            return IMoocJSONResult.errorMsg("");
        }
        Integer status = service.preconditionSearchFriends(myUserId, friendUsername);
        // 1、若用户不存在
        // 2、若添加自己
        // 3、若已经是自己好友
        if (status.equals(SearchFriendsStatusEnum.SUCCESS.status)) {
            Users friend = service.queryUserInfoByUsername(friendUsername);
            UsersVO usersVO = new UsersVO();
            BeanUtils.copyProperties(usersVO,friend);
            return IMoocJSONResult.ok(usersVO);
        } else {
            String errorMsg = SearchFriendsStatusEnum.getMsgByKey(status);
            return IMoocJSONResult.errorMsg(errorMsg);
        }
    }

    @PostMapping("/addFriendRequest")
    public IMoocJSONResult addFriendRequest(String myUserId, String friendUsername) throws InvocationTargetException, IllegalAccessException {
        // 0、判断参数是否为空
        if (StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUsername)) {
            return IMoocJSONResult.errorMsg("");
        }
        Integer status = service.preconditionSearchFriends(myUserId, friendUsername);
        // 1、若用户不存在
        // 2、若添加自己
        // 3、若已经是自己好友
        if (status.equals(SearchFriendsStatusEnum.SUCCESS.status)) {
            service.sendFriendRequest(myUserId,friendUsername);
        } else {
            String errorMsg = SearchFriendsStatusEnum.getMsgByKey(status);
            return IMoocJSONResult.errorMsg(errorMsg);
        }

        return IMoocJSONResult.ok();
    }

    @PostMapping("/queryFriendRequests")
    public IMoocJSONResult queryFriendRequests(String userId) throws InvocationTargetException, IllegalAccessException {
        //判断不能为空
        if(StringUtils.isBlank(userId)){
            return IMoocJSONResult.errorMsg("用户id不能为空");
        }
        //查询用户接收到的好友请求
        return IMoocJSONResult.ok(service.queryFriendRequestList(userId));
    }

    @PostMapping("/operFriendRequests")
    public IMoocJSONResult opreFriendRequest(String acceptUserId, String sendUserId, Integer operType){
        //判断参数
        if (StringUtils.isBlank(acceptUserId) || StringUtils.isBlank(sendUserId) || operType == null) {
            return IMoocJSONResult.errorMsg("");
        }
        if (OperatorFriendRequestTypeEnum.getMsgByType(operType) == null) {
            return IMoocJSONResult.errorMsg("");
        }

        //根据0 1进行不同的操作
        if (operType.equals(OperatorFriendRequestTypeEnum.IGNORE.type)) {
            //如果忽略请求，则删除在请求表中删除对应的请求
            service.deleteFriendRequest(sendUserId,acceptUserId);
        }
        if (operType.equals(OperatorFriendRequestTypeEnum.PASS.type)) {
            //如果是接受请求，
            // 1. 朋友关系表中添加对应数据
            // 2. 好友请求表中删除对应数据
            service.passFriendRequest(sendUserId,acceptUserId);
        }
        //返回更新后的好友列表
        List<MyFriendsVO> myFriends = service.queryMyFriends(acceptUserId);
        return IMoocJSONResult.ok(myFriends);
    }

    @PostMapping("/myFriends")
    public IMoocJSONResult myFriends(String userId){
        //判断参数
        if (StringUtils.isBlank(userId)) {
            return IMoocJSONResult.errorMsg("");
        }
        //查询好友列表并返回
        List<MyFriendsVO> myFriends = service.queryMyFriends(userId);
        return IMoocJSONResult.ok(myFriends);
    }
}
